package com.Jshop.user.controller;

import com.Jshop.user.pojo.User;
import com.Jshop.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 提供数据校验的接口
     * 检测用户的手机号和用户名是否已经被注册
     * */
    public ResponseEntity<Boolean> checkUserData(
            @PathVariable("data") String data,
            @PathVariable("type") Integer type
    ){
        Boolean aBoolean = this.userService.checkData(data, type);
        if (aBoolean == null){
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(aBoolean);
    }

    /**
     * 查询用户信息
     * */
    @GetMapping("query")
    public ResponseEntity<User> queryUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ){
        User user = this.userService.queryUser(username, password);
        System.out.println(user);
        if (user == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //注意用户信息的返回不会包含密码等敏感信息
        return ResponseEntity.ok(user);
    }

    /**
     * 增加用户积分
     * */
    @PutMapping("addPoint")
    public ResponseEntity<Boolean> addPoint(
            @RequestParam("username") String username
    ){
        Boolean isOK = this.userService.addPoint(username);
        return ResponseEntity.ok(isOK);
    }

    /**
     * 用户注册
     * */
    @PostMapping("register")
    public ResponseEntity<Void> register(
            @RequestParam("username") String username,
            @RequestParam("password") String password ){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        System.out.println(user);
        //参数校验
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())){
            return ResponseEntity.badRequest().build();
        }
        //命名冲突
        if (this.userService.queryByName(user.getUsername()) != null){
            return new ResponseEntity<>(HttpStatus.CONFLICT);
        }
        this.userService.register(user);
        return ResponseEntity.ok().build();
    }




}
